<template>
  <el-select class="width-100" :value="value" :clearable="clearable" @change="onChange" v-bind="$attrs">
    <el-option v-for="option in options" :key="option.dicKey" :label="option.dicValue" :value="option.dicKey">
    </el-option>
  </el-select>
</template>

<script>
import { loadDicCodeByDictionaryEncoList } from '@/api/sysDictionaryEnco'

export default {
  inheritAttrs: false,
  name: 'dictionary-picker',
  props: {
    value: String,
    dicCode: {
      type: String,
      required: true,
    },
    clearable: {
      type: Boolean,
      default: true,
    }
  },
  data () {
    return {
      internalValue: this.value,
      options: [],
    }
  },
  watch: {
    value (val) {
      this.internalValue = val
    },
  },
  mounted () {
    this.getOptions()
  },
  methods: {
    getOptions () {
      return loadDicCodeByDictionaryEncoList(this.dicCode).then(res => {
        if (res.code === 200) {
          this.options = res.data
        }
      })
    },
    onChange (value) {
      const option = this.options.find(v => v.dicKey === value)
      const name = option ? option.dicValue : ''
      this.$emit('input', value)
      this.$emit('change', { value, name, option })
    },
  },
}
</script>

<style scoped>

</style>
